package com.jzl.canal_consumer.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.annotation.JSONField;
import com.jzl.canal_consumer.config.CustomConfig;
import com.jzl.canal_consumer.bean.OpsDataSource;
import com.jzl.canal_consumer.service.MacService;
import com.jzl.canal_consumer.vo.OpsSourceVo;
import com.jzl.util.HttpClient;
import com.jzl.util.LoggerUtil;
import lombok.Data;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ZhenWuWang
 */
@Component
public class MacServiceImpl implements MacService
{
    private CustomConfig customConfig;

    private HttpClient httpClient;

//    @Value("${ops_data_source.macs}")
//    String macs;
//
//    @Value("${ops_data_source.shemas}")
//    String shemas;


    @Autowired
    public MacServiceImpl(CustomConfig customConfig, HttpClient httpClient)
    {
        this.customConfig = customConfig;
        this.httpClient = httpClient;
    }

    @Override
    public List<String> listMac()
    {
        try
        {
            List<OpsSourceVo> opsSourceVoList = getOpsSourceListByHttpRequest();
            if (opsSourceVoList == null || opsSourceVoList.isEmpty())
            {
                return Collections.emptyList();
            }
        } catch (IOException e)
        {
            e.printStackTrace();
        }
        return Collections.singletonList("00FFAABBCCDD");
    }

    @Override
    public List<OpsDataSource> listOpsDataSource()
    {
        if (customConfig.isMacRemote())
        {
            return listOpsDataSourceByRemote();
        } else
        {
            return listOpsDataSourceByLocal();
        }
    }

    private List<OpsDataSource> listOpsDataSourceByLocal()
    {
        String macs = customConfig.getOpsDataSourceMacs();
        String shemas = customConfig.getOpsDataSourceSchemas();
        if (StringUtils.isEmpty(macs) || StringUtils.isEmpty(shemas))
        {
            return Collections.emptyList();
        }

        String[] macArray = macs.split(",");
        String[] shemaArray = shemas.split(",");

        if (macArray.length == 0 || shemaArray.length == 0)
        {
            return Collections.emptyList();
        }

        List<OpsDataSource> opsDataSources = new ArrayList<>();
        for (int i = 0; i < macArray.length; i++)
        {
            System.out.println("--------------mac: " + macArray[i] + "   SchemaName：" + shemaArray[i]);
            OpsDataSource opsDataSource = new OpsDataSource();
            opsDataSource.setMac(macArray[i]);
            opsDataSource.setSchemaName(shemaArray[i]);
            opsDataSources.add(opsDataSource);
        }
        return opsDataSources;
    }


    private List<OpsDataSource> listOpsDataSourceByRemote()
    {
        try
        {
            List<OpsSourceVo> voList = getOpsSourceListByHttpRequest();
            if (voList != null && voList.size() > 0)
            {
                return voList.stream().map(vo ->
                {
                    OpsDataSource source = new OpsDataSource();
                    source.setMac(vo.getMac());
                    source.setSchemaName(vo.getSchemaName());
                    return source;
                }).collect(Collectors.toList());
            }
        } catch (IOException e)
        {
            e.printStackTrace();
        }

        return Collections.emptyList();
    }

    private List<OpsSourceVo> getOpsSourceListByHttpRequest() throws IOException
    {
        JSONObject requestPar = new JSONObject();
        requestPar.put("page", "1");
        requestPar.put("page_size", "100");
        String json = httpClient.postByJson(requestPar.toJSONString(), customConfig.getOpsUrl().concat("/").concat("auth/ops_source/list"));
        if (json == null || json.isEmpty())
        {
            LoggerUtil.error("OpsMacSource配置为空!");
        } else
        {
            TypeReference<com.jzl.vo.ResponseVo<PageVo>> typeReference = new TypeReference<com.jzl.vo.ResponseVo<PageVo>>()
            {
            };
            com.jzl.vo.ResponseVo<PageVo> responseVo = JSON.parseObject(json, typeReference);
            return responseVo.getData().opsSourceVos;
        }
        return Collections.emptyList();
    }

    @Data
    private static class PageVo
    {
        @JSONField(name = "total_page")
        private Integer totalPage;

        @JSONField(name = "total_size")
        private Integer totalSize;

        @JSONField(name = "ops_sources")
        private List<OpsSourceVo> opsSourceVos;
    }
}
